//
//  NYShowPictureViewController.m
//  百思不得姐
//
//  Created by Apple on 15/8/25.
//  Copyright (c) 2015年 Neal. All rights reserved.
//

#import "NYShowPictureViewController.h"
#import "NYTopicModel.h"
#import <SVProgressHUD.h>
#import <UIImageView+WebCache.h>

@interface NYShowPictureViewController ()<UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scroll_View;
/* imageV */
@property(nonatomic , weak) UIImageView *imageV;

@end

@implementation NYShowPictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *imageV = [[UIImageView alloc]init];
    //imageV.image = self.image;
    [imageV sd_setImageWithURL:[NSURL URLWithString:_topic.bigimage]];
    [self.scroll_View addSubview:imageV];
    self.imageV = imageV;
    /**
     用来装iad广告
     */
    UIView *bgview =[ [UIView alloc]init];
    bgview.backgroundColor = [UIColor redColor];
    [self.scroll_View addSubview:bgview];
    bgview.width = self.scroll_View.width;
    bgview.height = 50;

    self.imageV.userInteractionEnabled = YES;
    [self.imageV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissButton)]];
    
    //计算图片的frame
    imageV.x = 0 ;
    imageV.width = NYScreenW;
    imageV.height = imageV.width * self.topic.height / self.topic.width;
    
    if (imageV.height > NYScreenH) {//图片超过屏幕
        imageV.y = 0 ;
        bgview.y = CGRectGetMaxY(imageV.frame) + Margin;
        //设置内容的大小
        self.scroll_View.contentSize = CGSizeMake(0, imageV.height+50+2*Margin);
    } else {
        imageV.y =( NYScreenH - imageV.height)* 0.5;
        bgview.y = NYScreenH + Margin;

        self.scroll_View.contentSize = CGSizeMake(0, NYScreenH + +50+2*Margin );
    }

    //设置缩放比例
    CGFloat scale = self.topic.width/imageV.width;
    if (scale>1) {
        self.scroll_View.maximumZoomScale = scale;
    }
    
}
- (IBAction)dismissButton {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (IBAction)saveImage {
//保存图片的回调方法必须有3个参数，方法名可以随意
    UIImageWriteToSavedPhotosAlbum(self.imageV.image, self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    } else {
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
    }
}
#pragma mark - scrollView代理
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageV;
}
@end
